﻿using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Elight.Service.Interfaces;

namespace Elight.WebApi.Filters
{
    /// <summary>
    /// 表示一个特性，该特性用于验证用户是否有当前API的请求权限。
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AccessCheckedAttribute : ActionFilterAttribute, IOrderedFilter
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var httpContext = context.HttpContext;

            var isAuthenticated = httpContext.User.Identity.IsAuthenticated;

            var userId = Convert.ToInt32(httpContext.User.FindFirst("uid")?.Value);

            var requestPath = httpContext.Request.Path.ToString();
            var requestMethod = httpContext.Request.Method.ToString();

            var accessService = (IAccessService)httpContext.RequestServices.GetService(typeof(IAccessService));

            if (!isAuthenticated || !accessService.Validate(userId, requestPath, requestMethod))
            {
                context.Result = new UnauthorizedResult();
            }
        }
    }
}
